/* entity */
import Field from '@model/entity/Field';
/* model */
import { commonUseItemType } from '@src/component/AdvancedSearch/advancedSearch';
/* util */
import { getAdvancedFields, saveDataToStorage, getDataToStorage } from '@src/modules/projectManage/projectManageList/util';
import Log from '@src/util/log';
/* vue */
import { ref } from 'vue';

export function useAdvancedSearch() {
  // 高级搜索列
  let advanceSearchColumns = ref([] as Field[]);
  // 高级搜索常用字段
  let inCommonUse = ref([] as string[]);
  // 视图查询条件
  let viewportSearchModel = ref([]);
  
  // 构建高级搜索列
  const buildAdvancedColumns = (fields: Field[]) => {
    advanceSearchColumns.value = getAdvancedFields(fields);
  }

  // 常用字段切换
  const changeCommonUse = ({ fieldName, isChecked }: commonUseItemType, storageKey: string) => {
    const inCommonUseSet = new Set(inCommonUse.value);

    if (isChecked) {
      inCommonUseSet.add(fieldName);
    } else {
      inCommonUseSet.delete(fieldName);
    }

    inCommonUse.value = Array.from(inCommonUseSet);

    // 保存到缓存
    saveDataToStorage(storageKey, inCommonUse.value);
  }

  // 恢复常用字段
  const recoverCommonUse = async (storageKey: string) => {
    try {
      inCommonUse.value = await getDataToStorage(storageKey, []);
    } catch (error) {
      Log.error(error, '获取常用字段 recoverCommonUse');
      return Promise.reject(error);
    }
  }
  
  return {
    inCommonUse,
    viewportSearchModel,
    advanceSearchColumns,

    changeCommonUse,
    recoverCommonUse,
    buildAdvancedColumns,
  }
}